package SQLiteTest;

use strict;
our $DB_DIR   = "t/var";
our $DB_FILE  = "$DB_DIR/sqlite-test.db";
our $SQL_FILE = "t/lib/sqlite-test.sql";

sub get_test_schema {
    my $class = shift || 'Test::Schema';
    my @connect = _setup_db();
    my $schema = $class->connect( @connect );
    _init_db( $schema );
    return $schema;
}

sub _init_db {
    my $schema = shift;
    open my $sql_fh, "<", $SQL_FILE or die "Cannot open '$SQL_FILE' for read";
    my $sql_code;
    {
        local $/ = undef;
        $sql_code = <$sql_fh>;
    }
    close $sql_fh or die "Cannot close '$SQL_FILE' after read";
    $schema->storage->dbh->do( $_ )
        for split( /;\n+/, $sql_code );
    
}

sub _setup_db {
    unlink( $_ ) for grep { -f $_ } ( $DB_FILE, "$DB_FILE-journal" );
    mkdir( $DB_DIR ) unless -d $DB_DIR;
    return ( "dbi:SQLite:$DB_FILE", "", "", { AutoCommit => 1 } );
}

1;


package Test::Schema;
use base qw/ DBIx::Class::Schema /;

1;
